package com.kehutong.payfees.service;

import java.util.Set;
import java.util.stream.Collectors;

import com.kehutong.common.DoveClient;
import com.kehutong.common.Java8TimeUtils;
import com.kehutong.common.math.CalculatorUtils;
import com.kehutong.payfees.util.BasicClient;
import com.kehutong.payfees.util.FlowClient;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.webservice.WebService;

import com.kehutong.payfees.entity.record.ChargeRecord;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;

/**
 * 处理临时收费
 */
@WebService("/payfees/charge/temporary")
public class ChargeTemporaryServiceImpl{

    private static final Logger logger = LoggerFactory.getLogger(ChargeTemporaryServiceImpl.class);

    @Inject
    private DoveClient doveClient;
    @Inject
    private FlowClient flowClient;
    @Inject
    private BasicClient basicClient;
    @Inject
    private JdbcSession sqlSession;

    public void handlePaidChargeRecord(ChargeRecord cr, String attch) throws Exception{
        JSONObject jsonObject = JSONObject.parseObject(attch);

        String userId = jsonObject.getString("userId");
        String companyNo = jsonObject.getString("companyNo");

        final StringBuilder str = new StringBuilder();
        str.append("缴费成功通知，微信支付订单号:")
           .append(cr.getTransactionId())
                .append("，缴费金额：")
                .append(CalculatorUtils.formatMoney(cr.getAmt()))
                .append("元，缴费时间：")
                .append(Java8TimeUtils.parseString(cr.getChargeTime()));

        try {
            JSONObject result = doveClient.post("/message/webwork/sendAppText", http->{
                http.addParam("companyNo", companyNo);
                http.addParam("userId", userId);
                http.addParam("content", str.toString());
            });
            logger.trace("handlePaidChargeRecordByRoleId: {}", result.toJSONString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void handlePaidChargeRecordByRoleId(ChargeRecord cr, String attch) throws Exception {

        JSONObject jsonObject = JSONObject.parseObject(attch);
        String companyNo = jsonObject.getString("companyNo");
        String communityNo = jsonObject.getString("communityNo");

        JSONObject community = basicClient.getCommunityById(companyNo, communityNo);
        JSONArray employeeIds = community.getJSONArray("employee_ids");

        Set<String> userIds = getEmployeeMap(employeeIds);

        if(Objects.nonEmpty(userIds)){
            final StringBuilder str = new StringBuilder();
            str.append("缴费成功通知，微信支付订单号:")
                    .append(cr.getTransactionId())
                    .append("，缴费金额：")
                    .append(CalculatorUtils.formatMoney(cr.getAmt()))
                    .append("元，缴费时间：")
                    .append(Java8TimeUtils.parseString(cr.getChargeTime()));

            try {
                JSONObject result = doveClient.post("/message/webwork/sendAppText", http->{
                    http.addParam("companyNo", companyNo);
                    http.addParam("userId", String.join("|", userIds));
                    http.addParam("content", str.toString());
                });

                logger.trace("handlePaidChargeRecordByRoleId: {}", result.toJSONString());

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private Set<String> getEmployeeMap(JSONArray employeeIds) throws Exception{
        JSONObject result = doveClient.post("/kht-bin/wwout/getEmployeeByKhtIds",(http)->{
            JSONObject body = new JSONObject();
            body.put("khtIds", employeeIds);
            http.setBody(body.toJSONString());
        });

        if (result.getIntValue("code") == 200) {

            JSONArray data = result.getJSONArray("data");

            return data.stream().map(obj -> {
                JSONObject item = (JSONObject) obj;
                return item.getString("userId");
            }).collect(Collectors.toSet());
        }

        return null;
    }
}
